package com.macro.mall.common.lock;


import com.macro.mall.common.lock.redis.RedisLockConf;
import com.macro.mall.common.lock.redis.RedisWriteLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * redis锁工具
 *
 * @author 11519
 */
@Component
public class LockUtil {
    private static final String UUID_FLAG = UUID.randomUUID().toString();

    private static RedisWriteLock redisWriteLock;

    /**
     * 获取锁  锁超时默认30秒 ,锁等待2秒
     * @param lockKey 锁KEY
     * @return boolean
     */
    public boolean lock(String lockKey){
        return redisWriteLock.lock(lockKey);
    }

    /**
     * 获取锁
     * @param lockKey 锁KEY
     * @param expireTime 锁超时默认30秒
     * @param unit 单位
     * @return boolean
     */
    public boolean lock(String lockKey, long expireTime, TimeUnit unit){
        return redisWriteLock.lock(lockKey, expireTime, unit);
    }


    //@Autowired
    public void setRedisWriteLock(RedisWriteLock redisWriteLock){
        LockUtil.redisWriteLock = redisWriteLock;
    }

    public static String getWriteLockKey(String name){
        return RedisLockConf.WRITE_LOCK_PREFIX + name;
    }

    public static String getReentrantWriteLockKey(String name){
        return RedisLockConf.REENTRANT_WRITE_LOCK_PREFIX + name;
    }

    public static String getThreadUid(){
        return UUID_FLAG + ":" + Thread.currentThread().getId();
    }

    //读锁
    //private static volatile RedisReadLock redisReadLock;

    // 构建锁的key
    /*public static String getReadLockKey(String name){
        return RedisLockConf.READ_LOCK_PREFIX + name;
    }*/

    //双重检查锁实现单例
   /* public static RedisReadLock readLock(){
        if(redisReadLock == null){
            synchronized (RedisReadLock.class){
                if (redisReadLock == null){
                    redisReadLock = new RedisReadLock();
                }
            }
        }
        return redisReadLock;
    }*/
}

